package com.snow.exception;

import com.snow.utils.ApiResponse;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-22
 **/
@Setter
@Getter
public class SiteException extends RuntimeException {
    private static final Logger LOGGER = LoggerFactory.getLogger(SiteException.class);
    private String errorCode;
    private String [] errorMessageArgs;
    private ApiResponse apiResponse;
    public SiteException(String msg){
        super(msg);
        this.errorCode = "fail";
        this.errorMessageArgs = new String[0];
    }
    public SiteException(String msg,Throwable cause){
        super(msg,cause);
        this.errorCode = "fail";
        this.errorMessageArgs = new String[0];

    }
    protected SiteException(){
        this("");
    }
    public static SiteException withErrorCode(String code){
        SiteException siteException = new SiteException();
        siteException.errorCode = code;
        return siteException;
    }
    public static SiteException fromApiResponse(ApiResponse apiResponse){
        SiteException siteException = new SiteException();
        if(apiResponse == null){
            apiResponse = ApiResponse.fail("NULL");
        }
        siteException.apiResponse = apiResponse;
        return siteException;
    }
    public SiteException withErrorMessageAgs(String... ags){
        if(ags != null){
            this.errorMessageArgs = ags;
        }
        return this;

    }
    public ApiResponse response() {
        if(this.apiResponse != null) {
            return this.apiResponse;
        } else {
            this.apiResponse =ApiResponse.withCode(this.getErrorCode());
            if(this.getErrorMessageArgs() != null && this.getErrorMessageArgs().length > 0) {
                try {
                    this.apiResponse.setMsg(MessageFormat.format(this.apiResponse.getMsg(), this.getErrorMessageArgs()));
                } catch (Exception var2) {
                    LOGGER.error(var2.getMessage());
                }
            }

            return this.apiResponse;
        }
    }

}
